package com.borrowed.book.config.shiro;

import com.borrowed.book.system.util.StringUtils;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

public class ShiroSession extends DefaultWebSessionManager {
    /**
     * 定义请求头中使用的标记key,用来传递token
     */
    private static final String AUTH_TOKEN="Authorization";

    private static final String REFERENCED_SESSION_ID_SOURCE="stateless request";

    public ShiroSession(){
        super();
        //设置shirosession失效时间，默认30分钟
        setGlobalSessionTimeout(MILLIS_PER_MINUTE*30);//默认30分钟
    }

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        String sessionId= WebUtils.toHttp(request).getHeader(AUTH_TOKEN);
        if(StringUtils.isEmpty(sessionId)){
            return super.getSessionId(request,response);
        }else{
            //请求头中如果有 authToken, 则其值为sessionId
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);
            //sessionId
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, sessionId);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
            return sessionId;
        }
    }
}
